import 'package:report_sdk/src/models/event.dart';
import 'package:report_sdk/src/storage/storage_backend.dart' as impl;

class StorageBackend implements impl.StorageBackend {
  final List<Event> _memoryRecords = [];
  // 私有构造函数
  StorageBackend();

  @override
  Future<void> insertEvent(Event event) async {
    //上报前先插入内存
    //DateTime now = DateTime.now();
    _memoryRecords.add(event);
  }

  @override
  Future<List<Event>> getPendingEventsBatch(int batchSize) async {
    final List<Event> reportList = _memoryRecords.take(batchSize).toList();
    return reportList;
  }

  @override
  Future<void> deleteBatchEventByIds(List<String> ids) async {
    if (ids.isNotEmpty) {
      //变成从内存删除
      _memoryRecords.removeWhere((report) => ids.contains(report.id));
    }
  }

  @override
  Future<void> cleanOldEvents(int retentionDays) async {
    final cutoffDate = DateTime.now().subtract(Duration(days: retentionDays));
    _memoryRecords.removeWhere((event) => event.timestampMicros.isBefore(cutoffDate));
  }

  @override
  Future<void> dispose() async {
    _memoryRecords.clear();
  }
}
